/* 
	文件上传 - upload
 */

/* ------------------------------------------------------------------------------------
	模块导入
------------------------------------------------------------------------------------ */
// 第三方模块 - express
const express = require( 'express' )
// 第三方模块 - multer
const multer = require( 'multer' )

/* ------------------------------------------------------------------------------------
	常量、变量、方法
------------------------------------------------------------------------------------ */

// 新建路由
const uploadRouter = express.Router()

// 配置 multer
const storage = multer.diskStorage( {
	// 路径操作
	destination: ( req, file, cb ) => {
		cb( null, 'uploads/' )
	},
	// 文件名操作
	filename: ( req, file, cb ) => {
		const [ filename, extname ] = file.originalname.split( '.' )
		cb( null, filename + '-' + Date.now() + '.' + extname )
	}
} )

// var upload = multer({ storage: storage })
// 生成 multer 对象
const upload = multer( {
	storage
} )
// const upload = multer({ dest: 'uploads/' })
/* ------------------------------------------------------------------------------------
	路由配置
------------------------------------------------------------------------------------ */

// 上传文件
uploadRouter.post( '/', upload.single( 'file' ), ( req, res ) => {
	console.log( '上传文件' )
	if ( !req.file ) res.sendResult( null, 400, '没有文件' )
	// console.log( req.file.path )
	const path = req.file.path.replace( /\\/g, '/' )
	// console.log( filepath )
	res.sendResult( {
		path
	}, 200, '上传成功' )
} )

/* ------------------------------------------------------------------------------------
	导出路由
------------------------------------------------------------------------------------ */
module.exports = uploadRouter
